import 'package:znmm/UI/ProductPages/model/attributes_model.dart';
import 'package:znmm/UI/utils/my_global.dart';
import 'package:znmm/network/api_url.dart';
import 'package:znmm/network/dio_https.dart';
import 'package:znmm/network/graphql_service.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import '../model/product_model.dart';
import 'product_qlstr.dart';

class ProductMag {
  static final ProductMag _singleton = ProductMag._internal();
  factory ProductMag() {
    return _singleton;
  }

  ProductMag._internal();

  void doSomething() {
    print("Doing something...");
  }

  // late final List<ProductModel> _cartProducList = [];
  // List<ProductModel> getCartProducList() => _cartProducList;

  // void addToCart(ProductModel prodMol, {void Function()? callback}) {
  //   _cartProducList.add(prodMol);
  //   if (callback != null) {
  //     callback();
  //   }
  // }

  // ------------------------添加到购物车
  void addToCartReq(ProductModel pmodel, VariationsModel? variaModel, int iQty,
      List<String> selAttriStrList, String sourceUrl, String selColor,
      {void Function()? callback}) {
    // ignore: unused_local_variable
    Map<String, dynamic> dataMap = {};

    int databaseId = pmodel.databaseId; //唯一标记
    //可变产品
    if (pmodel.variaModelList.isNotEmpty && variaModel != null) {
      databaseId = variaModel.databaseId;

      Map<String, String> variationMap = {};
      for (int iIndex = 0;
          iIndex < variaModel.nodModelList.length &&
              iIndex < selAttriStrList.length;
          iIndex++) {
        NodelModel nodMoel = variaModel.nodModelList[iIndex];
        String keyStr = "attribute_${nodMoel.name}";
        String valStr = nodMoel.value;
        if (valStr.isEmpty) {
          valStr = selAttriStrList[iIndex];
        }

        variationMap[keyStr] = valStr;
      }

      dataMap = {
        "id": databaseId.toString(),
        "quantity": iQty.toString(),
        "variation": variationMap,
        "return_item": false,
      };

      //print("dataMap:$dataMap");
    } else {
      dataMap = {
        "id": databaseId.toString(),
        "quantity": iQty.toString(),
        "return_item": false,

        // "item_data": {
        //   "size": "1",
        //   "Color": "red",
        // }
      };
    }

    if (iQty <= 0) {
      MyGlobal.showInfo("QTY");
      return;
    }

    // print("sourceUrl:$sourceUrl");
    // print("name:${pmodel.name}-$selColor");
    // print("_iQty:$iQty");
    // print("price:${pmodel.price}");
    // print("databaseId:$databaseId");

    //String price = pmodel.price.replaceAll("\$", ""); //先移除 $
    //double fpriceValue = double.parse(price);
    //double totalPrice = fpriceValue * iQty;
    //String formattedPrice = totalPrice.toStringAsFixed(2);

    //这里是添加到本地缓存的
    // CnCartMag().addToCart(
    //   sourceUrl,
    //   "${pmodel.name}-$selColor",
    //   iQty,
    //   fpriceValue,
    //   //"\$$formattedPrice",
    //   databaseId,
    //   totalPrice,
    //   callback: callback,
    // );

    // dataMap = {
    //   "id": "659",
    //   "quantity": "1",
    //   "variation": {
    //     "attribute_plug-type": "EU",
    //     "attribute_color": "Rose gold",
    //   }
    // };

    //账号加入购物车
    // String username = UserInfoManage().username;
    // String password = UserInfoManage().password;
    // String basicAuth =
    //     'Basic ${base64Encode(utf8.encode('$username:$password'))}';

    //String urlStr = "/wp-json/cocart/v2/cart/add-item";

    print("添加都到购物车dataMap:$dataMap");

    //这里是网络的
    DioHttps dioUtil = DioHttps.instance!;
    //dioUtil.openLog();
    dioUtil
        .request<dynamic>(APIUrl.addTocartUrl,
            method: DioMethod.post,
            // options1: Options(headers: {
            //   "Authorization": basicAuth,
            // }),
            data: dataMap,
            bIsShowRequest: true,
            bIsShowResponse: true
            //baseUrlIndex: 1,
            )
        .then((response) {
      // 处理响应数据

      print("response:$response");
      if (response == null) return;
      MyGlobal.showInfo("success!");

      if (callback != null) {
        callback();
      }
    });
  }

  ////////-----------ALL Product
  String _afterStr = "";
  bool _hasNextPage = true;
  late final List<ProductModel> _allProducList = [];
  List<ProductModel> getAllProducList() => _allProducList;
  void reqAllProudut({bool showMore = false, void Function()? callback}) {
    // if (!showMore) {
    //   _allProducList.clear();
    //   afterStr = "";
    // }

    if ((!showMore && _allProducList.isNotEmpty)) return;

    if (!_hasNextPage) {
      MyGlobal.showInfo("No More Data!");
      return;
    }

    print("_afterStr$_afterStr");

    GraphQLService.performQuery(
      queryAll,
      HttpLink(APIUrl.graphqlUrl),
      variables: {
        'first': 20,
        'after': _afterStr.isNotEmpty ? _afterStr : "",
        // 'orderby': null,
        // 'featured': true,
        // 'categorySlug': "",
      },
      bIsShowLoading: true,
      //bShowResponse: true,
      (data) {
        if (data == null) {
          if (callback != null) {
            callback();
          }
          return;
        }
        // On success
        print('Query successful: $data');
        if (data['products'] == null) return;

        if (data['products']['pageInfo'] != null) {
          _afterStr = data['products']['pageInfo']["endCursor"] ?? "";
          _hasNextPage = data['products']['pageInfo']["hasNextPage"] ?? false;
        }

        var edgesList = data['products']['edges'] as List;
        print("edgesList:${edgesList.length}");
        for (int iIndex = 0; iIndex < edgesList.length; iIndex++) {
          var jsonVar = edgesList[iIndex]["node"];

          ProductModel pmodel = ProductModel();
          pmodel.name = MyGlobal.checkNullOrEmpty(jsonVar["name"]);
          pmodel.slug = MyGlobal.checkNullOrEmpty(jsonVar["slug"]);
          pmodel.sourceUrl =
              MyGlobal.checkNullOrEmpty(jsonVar["image"]["sourceUrl"]);
          pmodel.price = MyGlobal.checkNullOrEmpty(jsonVar["price"]);
          int iAverage = MyGlobal.checkNullOrZero(jsonVar['averageRating']);
          pmodel.averageRating = iAverage.toDouble();
          pmodel.stockStatus =
              MyGlobal.checkNullOrEmpty(jsonVar["stockStatus"]);

          _allProducList.add(pmodel);
        }

        print("_allProducList:${_allProducList.length}");

        if (callback != null) {
          callback();
        }
      },
    );
  }

  //------------ 根据 name 搜索
  List<ProductModel> getSearchByName({String name = ""}) {
    List<ProductModel> result = [];

    if (name.isEmpty) {
      result = _allProducList.toList();
    } else {
      for (var product in _allProducList) {
        if (product.name.toLowerCase().contains(name.toLowerCase())) {
          result.add(product);
        }
      }
    }

    return result;
  }
}
